﻿using Medlcalcare.MVC.Models;
using Microsoft.Extensions.Caching.Memory;
using Newtonsoft.Json;
using System.Net.Http.Headers;
using System.Text;

namespace Medlcalcare.MVC.Services
{
    /// <summary>
    /// DeepSeek智能客服核心服务
    /// </summary>
    public class DeepSeekService : IDeepSeekService
    {
        private readonly HttpClient _httpClient;
        private readonly IConfiguration _config;
        private readonly IMemoryCache _cache;

        public DeepSeekService(
            HttpClient httpClient,
            IConfiguration config,
            IMemoryCache cache)
        {
            _httpClient = httpClient;
            _config = config;
            _cache = cache;
        }

        /// <summary>
        /// 获取智能回复
        /// </summary>
        /// <param name="sessionId">会话ID</param>
        /// <param name="userInput">用户输入</param>
        /// <param name="context">历史上下文</param>
        public async Task<string> GetResponseAsync(
            string sessionId,
            string userInput,
            List<ChatMessage>? context = null)
        {
            var cacheKey = $"response_{sessionId}_{userInput.GetHashCode()}";

            // 缓存命中检查
            if (_cache.TryGetValue(cacheKey, out string? cachedResponse))
                return cachedResponse!;

            // 构建对话历史（保持上下文）
            var messages = new List<object>
            {
                new { role = "system", content = "你是一个专业客服助手，用中文回答，保持友好且专业" }
            };

            if (context?.Any() == true)
            {
                messages.AddRange(context.Select(x => new
                {
                    role = x.IsUser ? "user" : "assistant",
                    content = x.Content
                }));
            }

            messages.Add(new { role = "user", content = userInput });

            // 构造API请求
            var request = new
            {
                model = "deepseek-chat",
                messages,
                temperature = 0.7,
                max_tokens = 500
            };
            // 创建HTTP请求消息
            var requestMessage = new HttpRequestMessage(HttpMethod.Post, _config["DeepSeek:Endpoint"])
            {
                Headers = {
                Authorization = new AuthenticationHeaderValue("Bearer", _config["DeepSeek:ApiKey"])
            },
                Content = new StringContent(
                    JsonConvert.SerializeObject(request),
                    Encoding.UTF8,
                    "application/json")
            };
            // 发送请求
            // 发送请求并获取响应
            var response = await _httpClient.SendAsync(requestMessage);
            response.EnsureSuccessStatusCode(); // 确保HTTP状态码成功

            var result = await response.Content.ReadFromJsonAsync<DeepSeekResponse>();
            var reply = result?.Choices?.FirstOrDefault()?.Message?.Content ?? "抱歉，我无法理解您的问题";

            // 缓存响应（5分钟）
            _cache.Set(cacheKey, reply, TimeSpan.FromMinutes(5));

            return reply;
        }
        /// <summary>
        /// 解析大模型返回的原始文本
        /// </summary>
        /// <param name="rawText">模型输出的原始文本</param>
        /// <returns>结构化的诊断结果对象</returns>
        private string ParseDeepSeekResponse(string rawText)
        {
            // 示例解析逻辑（根据实际输出格式调整）
            //var sections = rawText.Split('\n');
            var sections = rawText.Replace("\n", "&lt;br&gt;");
            return FormatMedicalDiagnosis(rawText);
        }
        public string FormatMedicalDiagnosis(string input)
        {
            var sections = input.Split(new[] { "2. " }, StringSplitOptions.None);
            var diseasesSection = sections[0].Replace("1. ", "").Trim();
            var testsSection = "2. " + sections[1].Trim();

            var diseases = ParseDiseasesSection(diseasesSection);
            var tests = ParseTestsSection(testsSection);

            var sb = new StringBuilder();

            // 格式化疾病部分
            sb.AppendLine("### 1. 可能疾病（按概率排序）");
            sb.AppendLine();

            foreach (var disease in diseases)
            {
                sb.AppendLine($"- **{disease.Title}**");
                foreach (var detail in disease.Details)
                {
                    sb.AppendLine($"  - {detail}");
                }
                sb.AppendLine();
            }

            // 格式化检查项目部分
            sb.AppendLine("---");
            sb.AppendLine();
            sb.AppendLine("### 2. 建议检查项目");
            sb.AppendLine();

            foreach (var testGroup in tests)
            {
                sb.AppendLine($"#### {testGroup.Title}：");
                foreach (var test in testGroup.Details)
                {
                    sb.AppendLine($"- {test}");
                }
                foreach (var subGroup in testGroup.SubItems)
                {
                    sb.AppendLine($"  - {subGroup.Title}");
                    foreach (var item in subGroup.Details)
                    {
                        sb.AppendLine($"    - {item}");
                    }
                }
                sb.AppendLine();
            }

            // 添加备注
            var noteIndex = input.IndexOf("注：");
            if (noteIndex >= 0)
            {
                sb.AppendLine("---");
                sb.AppendLine();
                sb.AppendLine($"**备注**：{input.Substring(noteIndex + 2)}");
            }

            return sb.ToString();
        }

        private List<DiagnosisItem> ParseDiseasesSection(string text)
        {
            var diseases = new List<DiagnosisItem>();
            var diseaseParts = text.Split(new[] { " - **" }, StringSplitOptions.RemoveEmptyEntries);

            foreach (var part in diseaseParts)
            {
                if (string.IsNullOrWhiteSpace(part)) continue;

                var colonIndex = part.IndexOf("**：");
                if (colonIndex < 0) continue;

                var disease = new DiagnosisItem
                {
                    Title = part.Substring(0, colonIndex).Trim(),
                    Details = new List<string>()
                };

                var details = part.Substring(colonIndex + 3).Trim();
                disease.Details.Add(details);

                diseases.Add(disease);
            }

            return diseases;
        }

        private List<DiagnosisItem> ParseTestsSection(string text)
        {
            var tests = new List<DiagnosisItem>();
            var testGroups = text.Split(new[] { " - **" }, StringSplitOptions.RemoveEmptyEntries);

            foreach (var group in testGroups)
            {
                if (string.IsNullOrWhiteSpace(group)) continue;

                var colonIndex = group.IndexOf("**：");
                if (colonIndex < 0) continue;

                var testGroup = new DiagnosisItem
                {
                    Title = group.Substring(0, colonIndex).Trim(),
                    Details = new List<string>(),
                    SubItems = new List<DiagnosisItem>()
                };

                var content = group.Substring(colonIndex + 3).Trim();

                // 处理子项目
                var subItems = content.Split(new[] { " - " }, StringSplitOptions.RemoveEmptyEntries);
                foreach (var item in subItems)
                {
                    if (item.Contains("（视情况选择）"))
                    {
                        // 这是子组标题
                        var subGroup = new DiagnosisItem
                        {
                            Title = item.Replace("（视情况选择）", "").Trim(),
                            Details = new List<string>()
                        };
                        testGroup.SubItems.Add(subGroup);
                    }
                    else if (testGroup.SubItems.Count > 0)
                    {
                        // 添加到最后一个子组
                        testGroup.SubItems[^1].Details.Add(item.Trim());
                    }
                    else
                    {
                        // 添加到主组
                        testGroup.Details.Add(item.Trim());
                    }
                }

                tests.Add(testGroup);
            }

            return tests;
        }
    }

    // 对话消息模型
    public record ChatMessage(string Content, bool IsUser);

    public class DiagnosisItem
    {
        public string Title { get; set; }
        public List<string> Details { get; set; } = new List<string>();
        public List<DiagnosisItem> SubItems { get; set; } = new List<DiagnosisItem>();
    }
}
